package gov.kqqzyyy.monkey.pharmacyscreen.code.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SynthesizerListener;
import com.socks.library.KLog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.pharmacyscreen.R;
import gov.kqqzyyy.monkey.pharmacyscreen.code.adapter.MyGridViewAdapter;
import gov.kqqzyyy.monkey.pharmacyscreen.code.adapter.MyHJBRAdapter;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.CurrentVersion;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.PharmacyWindowBaseActivity;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.SpeakTool;
import gov.kqqzyyy.monkey.pharmacyscreen.code.object.HJBR;
import gov.kqqzyyy.monkey.pharmacyscreen.code.object.Patient;

@SuppressLint("NonConstantResourceId")
public class WMScreenActivity2 extends PharmacyWindowBaseActivity {

    @BindView(R.id.wm2_window_text)
    TextView mWindowText;
    @BindView(R.id.wm2_date_text)
    TextView mTimeText;
    @BindView(R.id.wm2_version_text)
    TextView mVersionText;
    @BindView(R.id.wm2_passed_gridview)
    GridView mPassedGridView;
    @BindView(R.id.wm2_call_gridview)
    GridView mCallGridView;
    @BindView(R.id.wm2_prepared_gridview)
    GridView mPreparedGridView;

    private String mWindowName;
    private String mWindowID;
    private String mPharmacyID;

    private List<HJBR> callList;

    private MyGridViewAdapter mPreparedAdapter;
    private MyHJBRAdapter mPassedAdapter;
    private MyHJBRAdapter mCallAdapter;

    private MyHandler handler;

    private SpeakTool speakTool;

    private CallThread callThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wmscreen2);
        ButterKnife.bind(this);
        onBindUI();
        handler = new MyHandler(this);

        speakTool = new SpeakTool(this);

        int textSize = 40;
        int textColor = R.color.colorGray;
        mPreparedAdapter = new MyGridViewAdapter(this);
        mPreparedAdapter.setTextSize(textSize);
        mPreparedAdapter.setTextColor(textColor);
        mPassedAdapter = new MyHJBRAdapter(this);
        mPassedAdapter.setTextSize(textSize);
        mPassedAdapter.setTextColor(textColor);
        mCallAdapter = new MyHJBRAdapter(this);
        mCallAdapter.setTextSize(textSize);
        mPreparedGridView.setAdapter(mPreparedAdapter);
        mCallGridView.setAdapter(mCallAdapter);
        mPassedGridView.setAdapter(mPassedAdapter);
    }

    @Override
    protected void onBindUI() {
        super.onBindUI();
        setTimeTextView(mTimeText);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWindowName = getmSharedPreferences().getString("window_name", "");
        mWindowID = getmSharedPreferences().getString("window_preference", "");
        mPharmacyID = getmSharedPreferences().getString("pharmacy_preference", "");
        if (mWindowName.equals("")) {
            Toast.makeText(getApplicationContext(), "请先设置药房窗口！", Toast.LENGTH_SHORT).show();
        } else {
            mWindowText.setText(mWindowName);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (speakTool != null) {
            speakTool.destory();
        }
        stopCallThread();
    }

    private void stopCallThread() {
        if (callThread != null) {
            callThread.interrupt();
        }
    }

    @Override
    public void doSetVersion() {
        super.doSetVersion();
        String text = "版本号：" + CurrentVersion.getVerName(this);
        mVersionText.setText(text);
    }

    @Override
    public void doFlushData() {
        super.doFlushData();
        doGetPatients(Integer.parseInt(mPharmacyID), mWindowID, true); //
    }

    @Override
    protected void doFilterData() {
        super.doFilterData();
        boolean isLag = false;
        List<Patient> patientList = getmResultList();
        List<Patient> preparedList = new ArrayList<>();
        if (patientList != null) {
            for (Patient patient : patientList
            ) {
                if (patient.getPYBZ().equals("1.0") && (patient.getFYBZ().equals("0.0") || patient.getFYBZ().equals("-1.0")) && patient.getJHPB().equals("0.0")) { //配好药,未发药
                    preparedList.add(patient);
                }
            }
            mPreparedAdapter.setPatientList(preparedList);
        }

        List<HJBR> hjbrList = getmHJBRList();
        callList = new ArrayList<>();
        List<HJBR> showCallList = new ArrayList<>();
        List<HJBR> passedList = new ArrayList<>();
        if (hjbrList == null) {
            isLag = true;
        } else {
            for (HJBR hjbr : hjbrList
            ) {
                if (hjbr.getCkbh() == Integer.parseInt(mWindowID.substring(0, 1))) {
                    for (int i = preparedList.size() - 1; i >= 0; i--) {
                        if (preparedList.get(i).getPDHM() == hjbr.getPdhm()) {
                            preparedList.remove(i);
                            break;
                        }
                    }
                    if (hjbr.getJhbz() == 0) {
                        showCallList.add(hjbr);
                        callList.add(hjbr);
                    } else {
                        if (isPassedPatient(hjbr.getWcsj())) {
                            passedList.add(hjbr);
                        } else {
                            showCallList.add(hjbr);
                        }
                    }
                }
            }
            if (getmSharedPreferences().getBoolean("window_of_call", false) && callList.size() > 0) {
                Collections.sort(callList, (arg0, arg1) -> arg0.getCzrq().compareTo(arg1.getCzrq()));
                doCallPatients();
            } else {
                isLag = true;
            }
            mPreparedAdapter.setPatientList(preparedList);
            mCallAdapter.setPatientList(showCallList);
            mPassedAdapter.setPatientList(passedList);
        }

        if (isLag) {
            new CountDownTimer(getMyApplication().getTimeDelay(), 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    doFlushData();
                }
            }.start();
        }
    }

    //呼叫病人操作
    protected void doCallPatients() {
        stopCallThread();
        callThread = new CallThread();
        callThread.start();
        new CallThread().start();
    }

    //呼叫病人线程
    private class CallThread extends Thread {

        private boolean keepCalling = true;
        private boolean callNext = true;
        private int index = 0;

        @Override
        public void run() {
            super.run();
            while (keepCalling) {
                if (callNext) {
                    callNext = false;
                    HJBR patient = callList.get(index);
                    Message message = new Message();
                    message.what = 0x29;
                    message.arg1 = patient.getPdhm();
                    handler.sendMessage(message);

                    String speakMessage = "请 " + patient.getPdhm() + " 号 " + patient.getBrxm() + " 到 " + mWindowName + " 取药 ";
                    speakMessage += " " + speakMessage;
                    speakTool.speak(speakMessage, listener);
                    //更新标识
                    doUpdateXYJHPB(patient);
                }
                try {
//                    Thread.sleep(1000);
                    SystemClock.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        private final SynthesizerListener listener = new SynthesizerListener() {
            @Override
            public void onSpeakBegin() {
            }

            @Override
            public void onBufferProgress(int percent, int beginPos, int endPos, String info) {

            }

            @Override
            public void onSpeakPaused() {
            }

            @Override
            public void onSpeakResumed() {
            }

            @Override
            public void onSpeakProgress(int percent, int beginPos, int endPos) {

            }

            @Override
            public void onCompleted(SpeechError speechError) {
                KLog.d("APE", index);
                if (index == callList.size() - 1) {
                    keepCalling = false;
                    callNext = false;
                    Message message = new Message();
                    message.what = 0x29;
                    message.arg1 = -1;
                    handler.sendMessage(message);
                    doFlushData();
                } else {
                    index++;
                    callNext = true;
                }
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {
            }
        };

    }

    private static class MyHandler extends Handler {

        WeakReference<WMScreenActivity2> mActivity;

        MyHandler(WMScreenActivity2 activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            WMScreenActivity2 activity = mActivity.get();
            if (msg.what == 0x29) {
                if (msg.arg1 == -1) {
                    activity.stopCallThread();
                }
                activity.mCallAdapter.setPDHM(msg.arg1);
            }
        }
    }

    @Override
    protected void doRollingGridView() {
        super.doRollingGridView();
        rollingGridView(mPassedGridView, 2);
        rollingGridView(mPreparedGridView, 1);
        rollingGridView(mCallGridView, 2);
    }
}
